package com.xh.demo.commons.entity;

import com.xh.demo.commons.enums.ApiCodeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Getter
@Setter
public class ApiResponse<T> {

    /**
     * 响应状态码
     */
    private String code;

    /**
     * 提示信息
     */
    private String msg;

    /**
     * 时间搓
     */
    private long timestamp;

    /**
     * 数据
     */
    private T data;

    /**
     * 签名
     */
    private String sign;


    public static <T> ApiResponse<T> success(T data) {
        return response(ApiCodeEnum.SUCCESS.getCode(), ApiCodeEnum.SUCCESS.getMsg(), data);
    }

    public static <T> ApiResponse<T> error(String code, String msg) {
        return response(code, msg, null);
    }

    public static <T> ApiResponse<T> response(String code, String msg, T data) {
        ApiResponse<T> response = new ApiResponse<>();
        response.setCode(code);
        response.setMsg(msg);
        response.setData(data);
        response.setTimestamp(System.currentTimeMillis());
//        String sign = signData(data);
        response.setSign(null);
        return response;
    }

    /**
     * @param data 反射的对象,获取对象的字段名和值
     */
    public static Map<String, String> getFields(Object data) throws IllegalAccessException, IllegalArgumentException {
        if (data == null) return null;
        Map<String, String> map = new HashMap<>();
        Field[] fields = data.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(data);
            if (field.get(data) != null) {
                map.put(name, value.toString());
            }
        }
        return map;
    }

}
